package com.example.filter;

import com.alibaba.fastjson2.JSONObject;
import com.example.pojo.vo.LoginUser;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token请求头
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 解析token获取用户id
        String userId;
        try {
            Claims claims = JwtUtils.parseToken(token);
            userId = String.valueOf(claims.get("userId"));
        } catch (Exception e) {
            /**
             * 1.这里的异常不会被springboot的异常处理机制处理
             * 2.解决方案
             *  1.抛出异常给springSecurity进行处理，需要实现AuthenticationEntryPoint
             *  2.或者在catch中自己使用respone进行响应
             * */
            throw new RuntimeException("token非法");
        }
        // 在redis获取用户信息
        String redisKey = "login:" + userId;
        Object obj = redisTemplate.opsForValue().get(redisKey);
        // 将用户信息存入SecurityContextHolder
        LoginUser loginUser = null;
        if (obj != null) {
            if (obj instanceof LoginUser) {
                loginUser = (LoginUser) obj;
            } else {
                // 如果是JSONObject，则使用JSON工具转换
                JSONObject jsonObject = (JSONObject) obj;
                loginUser = jsonObject.toJavaObject(LoginUser.class);
            }
        }
        // 将用户信息存入SecurityContextHolder
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录");
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,
                null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }
}
